package com.jastar.android.util;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FileUtil {

    public static List<String> readRawLines(Resources resources, int id) {
        try (InputStream inputStream = resources.openRawResource(id)) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                return reader.lines().collect(Collectors.toList());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveText(String path, String txt) {
        try (BufferedWriter os = new BufferedWriter(new FileWriter(path))) {
            os.write(txt);
        } catch (IOException e) {
            Log.e("FAIL", "Exception when save text.", e);
        }
    }

    public static String openText(String path) {
        StringBuilder builder = new StringBuilder();
        try (BufferedReader is = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = is.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            Log.e("FAIL", "Exception when open text.", e);
        }
        return builder.toString();
    }

    public static void saveImage(String path, Bitmap bitmap) {
        try (FileOutputStream fos = new FileOutputStream(path)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Bitmap openImage(String path) {
        try (FileInputStream fis = new FileInputStream(path)) {
            return BitmapFactory.decodeStream(fis);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void clear(File file) {
        if (!file.exists()) return;
        if (file.isFile()) {
            Log.i("DEL", "删除文件：" + file.getPath());
            file.deleteOnExit();
            return;
        }
        Arrays.stream(file.listFiles()).forEach(f -> clear(f));
    }

}